cmake_minimum_required(VERSION 3.4)

project(cuda)
enable_testing()

set(CMAKE_CXX_STANDARD 17)
set(CUDA_NVCC_FLAGS ${CUDA_NVCC_FLAGS} -O3 --ptxas-options=-v)

set(CUBLAS_HINTS ${CUDA_ROOT} $ENV{CUDA_ROOT} $ENV{CUDA_TOOLKIT_ROOT_DIR})
set(CUBLAS_PATHS /usr/local/cuda)
set(CUDA_TOOLKIT_ROOT_DIR /usr/local/cuda)

# Finds the include directories
find_path(CUBLAS_INCLUDE_DIRS
  NAMES cublas_v2.h cuda.h
  HINTS ${CUBLAS_HINTS}
  PATH_SUFFIXES include inc include/x86_64 include/x64
  PATHS ${CUBLAS_PATHS}
  DOC "cuBLAS include header cublas_v2.h"
)
mark_as_advanced(CUBLAS_INCLUDE_DIRS)

# Finds the libraries
find_library(CUDA_LIBRARIES
  NAMES cudart
  HINTS ${CUBLAS_HINTS}
  PATH_SUFFIXES lib lib64 lib/x86_64 lib/x64 lib/x86 lib/Win32 lib/import lib64/import
  PATHS ${CUBLAS_PATHS}
  DOC "CUDA library"
)
mark_as_advanced(CUDA_LIBRARIES)
find_library(CUBLAS_LIBRARIES
  NAMES cublas
  HINTS ${CUBLAS_HINTS}
  PATH_SUFFIXES lib lib64 lib/x86_64 lib/x64 lib/x86 lib/Win32 lib/import lib64/import
  PATHS ${CUBLAS_PATHS}
  DOC "cuBLAS library"
)
mark_as_advanced(CUBLAS_LIBRARIES)
find_package(CUDA REQUIRED)

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)

aux_source_directory(src/app APP_FILES)
foreach(app_file ${APP_FILES})
    get_filename_component(suffix ${app_file} EXT)
    string(REPLACE ".cu" "" app_name ${app_file})
    string(REPLACE ".cc" "" app_name ${app_name})
    string(REPLACE ".cpp" "" app_name ${app_name})
    string(REPLACE "src/app/" "" app_name ${app_name})
    if (suffix STREQUAL ".cu")
      cuda_add_executable(${app_name} ${app_file})
      target_link_libraries(${app_name} ${CUBLAS_LIBRARIES} ${CUDA_CUDART_LIBRARY})
    else()
      add_executable(${app_name} ${app_file})
    endif()
endforeach()

aux_source_directory(src/tests TEST_FILES)
foreach(test_file ${TEST_FILES})
    get_filename_component(suffix ${test_file} EXT)
    string(REPLACE ".cu" "" test_name ${test_file})
    string(REPLACE ".cc" "" test_name ${test_name})
    string(REPLACE ".cpp" "" test_name ${test_name})
    string(REPLACE "src/tests/" "" test_name ${test_name})
    if (suffix STREQUAL ".cu")
      cuda_add_executable(${test_name} ${test_file})
      target_link_libraries(${test_name} ${CUBLAS_LIBRARIES} ${CUDA_CUDART_LIBRARY})
    else()
      add_executable(${test_name} ${test_file})
    endif()
endforeach()